package com.woniuxy.factories;



import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public final class BeanFactory {

    private static Map<String, Object> map = new ConcurrentHashMap<>();

    public volatile static BeanFactory beanFactory = null;

    //获得锁对象
    private static Lock lock = new ReentrantLock();

    //私有化构造器
    private BeanFactory() {
    }


    static {
        initBeanFactory();
    }


    //获得单例对象的方法


    public static BeanFactory getBeanFactory() {

        if (beanFactory == null) {

            // synchronized (BeanFactory.class){
            //上锁
            lock.lock();
            if (beanFactory == null) {
                beanFactory = new BeanFactory();
            }
            //解锁
            lock.unlock();
            //}
        }

        return beanFactory;
    }


    private static void initBeanFactory() {
        InputStream is = null;
        try {
            //获得配置文件所在的地方

            is = Class.forName("com.woniuxy.factories.BeanFactory").getResourceAsStream("person.properties");

            //创建 Properties 读取配置文件
            Properties properties = new Properties();
            properties.load(is);

            //获得配置文件的所有key
            Set<String> strings = properties.stringPropertyNames();

            for (String str : strings) {
                //遍历配置文件创建对象
                map.put(str, properties.getProperty(str));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public Object getBean(String className) {
        Object object = null;
        try {
            object = Class.forName((String) map.get(className)).newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return object;
    }

}
